####################################################################
#   Assignment: expression model on chr
#   Date: Apr 17, 2020
####################################################################

install.packages("ggplot2")
library(ggplot2)
options(stringsAsFactors = F)
##01.fpkm matrix
load(file = "logdata.chr1.Rdata")
head(logdata)
## gene len
len<-read.delim("chr01.len.txt",
           header = T,
           stringsAsFactors = F,
           sep = "\t")
## merge
logdata$Pos <- len$Start
## convert into ggplot2 data
ggdata <- list()
cultivar <- colnames(logdata)
for (i in 1:(ncol(logdata)-1)) {
  ggdata[[i]] <- data.frame(GID = rownames(logdata),
                            Pos = logdata$Pos,
                            fpkm = logdata[,i],
                            cultivar = cultivar[i])
}
data.tmp1 <- bind_rows(ggdata)
head(data.tmp1)
## cultivar label
data.tmp1$cultivar = factor(data.tmp1$cultivar,levels = cultivar)
cul.continue <- data.frame(cultivar = cultivar,
                           cultivar_continue = c(1:length(cultivar))*2)
data.final <- merge(data.tmp1,cul.continue,
                    by = "cultivar")
data.final$Pos = data.final$Pos/1000000
head(data.final)

exprofile <- ggplot(data.final,aes(x = Pos, y = cultivar_continue)) +
  geom_linerange(aes(ymin=cultivar_continue-0.5,ymax = cultivar_continue+0.5,color = fpkm), size=0.5)+
  scale_y_continuous(breaks = cul.continue$cultivar_continue,labels = cultivar, expand = c(.01,0),name = "")+
  scale_x_continuous(breaks = c(seq(0,110,10)),expand = c(.01,0),name = "Position /Mb")+
  scale_color_gradient(high="red",low = "white",
                       na.value = "white",
                       breaks=c(0,1,3),
                       labels=c("0","1","larger than 3"),
                       limits=c(0,3),
                       name=""
  )+
  labs(title = "Gene expression profile of Chr01") +
  theme_bw()+
  theme(
    panel.grid = element_blank(),
    axis.text.y = element_text(face = "bold.italic",
                               size = 3,)
  )
exprofile
